//
//  CWShortVideoContainer.swift
//  SwiftTest
//
//  Created by 陈旺 on 2022/1/25.
//

import UIKit

/// 整体模块
class CWShortVideoContainer: UIView {

    private lazy var scroll: CWShortVideoCollection = {
        let target = CWShortVideoCollection.init(frame: CGRect.zero)
            .link
            .dataSource(self)
            .delegate(self)
            .prefetchDataSource(self)
            .showsVerticalScrollIndicator(false)
            .end
        target.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        target.register(CWShortVideoCollectionCell.self, forCellWithReuseIdentifier: "\(CWShortVideoCollectionCell.self)")
        return target
    }()

    /// 右边的抽屉
    private lazy var rightSheet: CWShortVideoRightSheet = {
        let rightList = CWShortVideoRightSheet.init(frame: CGRect.zero)
        return rightList
    }()

    /// 右边抽屉的宽度
    private var rightSheetWidth: CGFloat {
        return 100
    }

    /// 右边抽屉的约束（动态修改）
    private var rightSheetRightMargin: NSLayoutConstraint!

    /// 侧滑手势最后一次x偏移
    private var lastPanX: CGFloat = 0

    /// 是否正在展示右边的抽屉
    private var isShowRightSheet: Bool {
        return rightSheetRightMargin.constant == 0
    }

    private var currentIndex: Int = 0

    //MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        configureSelf()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    //MARK: - UI绘制
    private func configureSelf() {
        configureScroll()
        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(panHandler(_:)))
        isUserInteractionEnabled = true
        addGestureRecognizer(pan)
    }

    private func configureScroll() {
        let map: [String: UIView] = [
            "scroll": scroll,
            "rightSheet": rightSheet
        ]
        map.addTo(self)
        withVFL("V:|[rightSheet]|", views: map)
        withVFL("H:|[scroll]|", views: map)
        withVFL("V:|[scroll]|", views: map)
        withVFL("H:[rightSheet(\(rightSheetWidth))]", views: map)
        rightSheetRightMargin = rightSheet.rightAnchor.constraint(equalTo: self.rightAnchor, constant: rightSheetWidth).setIsActive(true)
        scroll.reloadData()
        bringSubviewToFront(rightSheet)
    }

    private func percentForRightMenuSheet(_ value: CGFloat) -> CGFloat {
        return -(value / rightSheetWidth) + 1
    }


    //MARK: - 事件回调
    @objc private func panHandler(_ pan: UIPanGestureRecognizer) {

        defer {
            pan.setTranslation(CGPoint.zero, in: pan.view)
        }

        let point = pan.translation(in: pan.view)
        let x = point.x
        switch pan.state {
        case .began:()
        case .changed:
            let current = rightSheetRightMargin.constant
            var target = current + x
            target = min(rightSheetWidth, target)
            target = max(0, target)
            rightSheetRightMargin.constant = target
            lastPanX = x
            // 计算出动画百分比
            let p: CGFloat = percentForRightMenuSheet(target)
            currentCell()?.move(p, total: rightSheetWidth)
        case .ended:fallthrough
        case .failed:fallthrough
        case .cancelled:
            let show = lastPanX < 0
            showRightSheet(show: show)
        case .possible:()
        @unknown default:()
        }
    }

    //MARK: - 业务逻辑
    private func showRightSheet(show: Bool = true, animation: Bool = true) {

        defer {
            lastPanX = 0
        }

        let timeInterval = 0.25
        let value = show ? 0 : rightSheetWidth
        var percent = percentForRightMenuSheet(rightSheetRightMargin.constant)
        percent = show ? (1 - percent) : percent
        if animation {
            UIView.animate(withDuration: timeInterval * percent) { [weak self] in
                guard let `self` = self else {return}
                self.rightSheetRightMargin.constant = value
                let p = self.percentForRightMenuSheet(value)
                self.currentCell()?.move(p, total: self.rightSheetWidth)
                self.layoutIfNeeded()
            } completion: {  finished in

            }
            return
        }
        self.rightSheetRightMargin.constant = value
    }


    /// 拿到当前正在展示的那个cell
    /// - Returns: CWShortVideoCollectionCell
    fileprivate func currentCell() -> CWShortVideoCollectionCell? {
        guard let cell = scroll.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? CWShortVideoCollectionCell else {
            return nil
        }
        return cell
    }
}

//MARK: - collectionView代理回调
extension CWShortVideoContainer: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if isShowRightSheet {
            showRightSheet(show: false, animation: true)
            return
        }
        debugPrint("\(indexPath.row)")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10;
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(CWShortVideoCollectionCell.self)", for: indexPath) as? CWShortVideoCollectionCell else {
            return collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        }
        let urls = [
            "https://media.w3.org/2010/05/sintel/trailer.mp4",
            "https://media.w3.org/2010/05/video/movie_300.mp4",
            "https://image.shanghaiqixiu.org/dev/dt/pany/202012/06c44a1e159e48e6b95f16cb35b9d02b"
        ]
        cell.titleLab.text = "\(indexPath.row % 3 + 1)"
        let url = urls[indexPath.row % 3]
        if indexPath.row % 3 == currentIndex {
            cell.playerView.play(url)
        }else {
            cell.playerView.load(url)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let _cell = cell as? CWShortVideoCollectionCell else {
            return
        }
        let p: CGFloat = isShowRightSheet ? 1 : 0
        _cell.move(p, total: rightSheetWidth)
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        // cell消失的时候，暂停播放
        guard let _cell = cell as? CWShortVideoCollectionCell else {return}
        _cell.playerView.pause()
    }

    //MARK: - 滑动代理
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        // 开始拖拽，暂停播放
        scroll.visibleCells.forEach { cell in
            if let item = cell as? CWShortVideoCollectionCell {
                item.playerView.pause()
            }
        }
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        // 结束拖拽
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // 结束拖拽
    }

    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        // 开始减速
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 减速完毕
        var index = floor(scrollView.contentOffset.y / scrollView.bounds.height)
        if index == 9 {
            index = 0
            currentIndex = Int(index)
            scroll.scrollToItem(at: IndexPath.init(row: 0, section: 0), at: .centeredVertically, animated: false)
        }
        currentIndex = Int(index)
        let indexPath = IndexPath.init(row: Int(index), section: 0)
        if let cell = scroll.cellForItem(at: indexPath) as? CWShortVideoCollectionCell {
            cell.playerView.play()
        }
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        // 动画结束

    }
}

extension CWShortVideoContainer: UICollectionViewDataSourcePrefetching {

    func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
        // 预加载
    }

    func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
        // 预销毁
    }
}

